package com.syy.spider.service.impl;

import com.syy.spider.dao.SpiderMapper;
import com.syy.spider.pojo.Picture;
import com.syy.spider.pojo.User;
import com.syy.spider.pojo.User_title;
import com.syy.spider.service.SpiderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class SpiderServiceImpl implements SpiderService {
    @Autowired
    private SpiderMapper spiderMapper;

    //获取到网站源码
    @Override
    public String getHtml(String name) {
        //定义网页源码
        StringBuilder WebSourceCode = new StringBuilder();
        //用户输入想要爬取的对象后，系统给出的爬取链接
        String html = "https://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&word=" + name + "&pn=0";
        try {
            //建立连接
            URL url = new URL(html);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setDoInput(true);
            httpUrlConn.setRequestMethod("GET");
            httpUrlConn.setRequestProperty("Accept", "*/*");
            httpUrlConn.setRequestProperty("accept-language", "zh-CN,zh;q=0.9");
            httpUrlConn.setRequestProperty("Connection", "keep-alive");
            httpUrlConn.setRequestProperty("cookie", "BDUSS=UhMSHo4bkhlbG1WWFF4ZGVWelNkMmNvYXhrQlF1WUI4LUJoOWNRVlpueXVpUlJpSVFBQUFBJCQAAAAAAAAAAAEAAAAiwpznuOfO3bb3ODcxAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAK787GGu~Oxhd; BDUSS_BFESS=UhMSHo4bkhlbG1WWFF4ZGVWelNkMmNvYXhrQlF1WUI4LUJoOWNRVlpueXVpUlJpSVFBQUFBJCQAAAAAAAAAAAEAAAAiwpznuOfO3bb3ODcxAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAK787GGu~Oxhd; __yjs_duid=1_0a12f8f877dcd41c159e3c259a7524251642923041622; BIDUPSID=BE79C9480725AD7628E9A460E54933C3; PSTM=1642924923; BAIDUID=1A9812ACB6F24CD5BAF4D4139A139E87:FG=1; BAIDUID_BFESS=1A9812ACB6F24CD5BAF4D4139A139E87:FG=1; BDSFRCVID_BFESS=0uAOJeC62Zf8zL5HNjMk-fdeZ1l8hN7TH6aoIrF3s7FBMPnCmqTFEG0PKM8g0KuMjd8qogKKKgOTHICF_2uxOjjg8UtVJeC6EG0Ptf8g0f5; H_BDCLCKID_SF_BFESS=tbF8VILXJC-3e-ngMRrWq4kHhMcf2TKXbIOjVhc9Jp7keq8CDR7bbJkQ0t7waDrKHCcb0xcY5-TkVUo2y5jHhUPZDMbiBPJutD7Lb-QEBIopsIJMjfFWbT8Uj-chBfTXaKviahvjBMb1OqODBT5h2M4qMxtOLR3pWDTm_q5TtUJMeCnTD-Dhe6JBDNDDJT8jfKvKWRK8-JKKqbRp2DTjhPrMDhoCWMT-0bFHhJLyMq4hOhrFXt4Vb408WGQQqPvwJan7_JjOW4oPhP86Qx5Y0-CdhqQn0fQxtNRi2Cnjtpvh8JcgebQobUPUyUJ9LUvA02cdot5yBbc8eIna5hjkbfJBQttjQn3hfIkj0DKLK-oj-DDCDj8b3e; BAIDU_WISE_UID=wapp_1642953033710_913; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; delPer=0; PSINO=3; BDRCVFR[dG2JNJb_ajR]=mk3SLVN4HKm; BDRCVFR[feWj1Vr5u3D]=I67x6TjHwwYf0; H_PS_PSSID=34429_35106_31254_35831_35488_34584_35491_35872_35245_35317_26350_35884_35878_35746; BA_HECTOR=04ah0hah01a12021mj1h0htn00q; userFrom=www.baidu.com; ab_sr=1.0.1_MzAzNTQwNGE5NTYzNTVhMDk2NzkxZjM5ZGMyMGRkMjk5OTY2MGI0NzEwMTQ0OTNkMGQ4NWZkZmU3NzlmNmZjNzgxMzQzYTM2ZmRhMjlhMjFjODZjZDM5YzZhNzcyNTU2YWRlZGE0MjY4MmI0NmQxMjRmMjBiMmE1ZDFhNjA1NDJjMDg4NWJkMDcxMzdiNzEwNjIxYTVkOTA3NzI0Y2M1ZGZmN2EzNjI3YjBjMzA4OTQ3N2Y5YzdiNWNmN2NmNmFh");
            httpUrlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36");
            //获取输入流
            InputStream input = httpUrlConn.getInputStream();
            //将字节输入流转换为字符输入流
            InputStreamReader read = new InputStreamReader(input, "utf-8");
            //为字符输入流添加缓冲
            BufferedReader br = new BufferedReader(read);
            // 读取返回结果
            String data = null;
            while ((data = br.readLine()) != null) {
                WebSourceCode.append(data);
            }
            // 释放资源
            br.close();
            read.close();
            input.close();
            httpUrlConn.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return WebSourceCode.toString();
    }

    @Override
    public Picture getImgsUrlAndDescription(String code) {
        Picture picture = new Picture();
        String regex1 = "\"thumbURL\":\"[\\w\\d:/.=,&?]*\"";
        String regex3 = "\"FromURL\":\"http:[\\\\/\\w.\\d,]*";
        Matcher reg1 = Pattern.compile(regex1).matcher(code);
        while (reg1.find()) {
            String imgCode = reg1.group(0);
            imgCode = imgCode.replace("\"thumbURL\":\"", "");
            imgCode = imgCode.replace("\"", "");
            picture.setJustImgUrl(imgCode);
            break;
        }

        int start = code.lastIndexOf("fromPageTitleEnc");
        int end = code.lastIndexOf("bdSourceName");
        String desCode = code.substring(start, end);
        desCode = desCode.replace("fromPageTitleEnc\":\"", "");
        int i = desCode.lastIndexOf(",");
        desCode = desCode.substring(0, i);
        desCode = desCode.replace("\"", "");
        picture.setDescription(desCode);

        Matcher reg3 = Pattern.compile(regex3).matcher(code);
        while (reg3.find()) {
            String url = reg3.group(0);
            url = url.replace("\"FromURL\":\"", "");
            url = url.replaceAll("\\\\", "");
            picture.setUrl(url);
            break;
        }
        return picture;
    }

    @Override
    public void downLoad(Picture picture) throws IOException {
        URLConnection con = null;
        try {
            // 构造URL
            URL url = new URL(picture.getJustImgUrl());
            // 打开连接
            con = url.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 输入流
        InputStream is = con.getInputStream();
        // 1K的数据缓冲
        byte[] bs = new byte[1024];
        // 读取到的数据长度
        int len;
        // 输出的文件流
//        int i = pictures.getUrl().lastIndexOf(".");
//        System.out.println(pictures.getName());
//        String substring = pictures.getUrl().substring(i + 1, pictures.getName().length() - 1);
//        System.out.println(substring);
        String name = UUID.randomUUID().toString();
        picture.setName(name);
        String filename = "D:/Spider/img/" + name + ".jpg";  //下载路径及下载图片名称
        picture.setPath(filename);
        File file = new File(filename);
        FileOutputStream os = new FileOutputStream(file, true);
        // 开始读取
        while ((len = is.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
//        spiderMapper.insertPicInfo(picture);
        // 完毕，关闭所有链接
        os.close();
        is.close();
    }

    @Override
    public List<Picture> getImgs(String username,String title) {
        List<Picture> pictures = spiderMapper.getImgs(username,title);
        return pictures;
    }

    @Override
    public void insertPicInfo(Picture picture) {
        spiderMapper.insertPicInfo(picture);
    }

    @Override
    public User_title selectUserTitle(String username, String spiderName) {
        return spiderMapper.selectUserTitle(username,spiderName);
    }

    @Override
    public void insertTitle(String user, String spiderName) {
        spiderMapper.insertTitle(user,spiderName);
    }

    @Override
    public List<User_title> getUserTitle(String username) {
        return spiderMapper.getUserTitle(username);
    }

    @Override
    public String getTitle(Integer id) {
        return spiderMapper.getTitle(id);
    }

    @Override
    public Picture selectPictureById(int picId) {
        return spiderMapper.selectPictureById(picId);
    }

    @Override
    public int deleteFav(int id) {
        return spiderMapper.deleteFav(id);
    }

    @Override
    public List<Picture> selectPicturesByTitle(String username,String title) {
        return spiderMapper.selectPicturesByTitle(username,title);
    }

    @Override
    public void deleteTitle(String username, String title) {
        spiderMapper.deleteTitle(username,title);
    }
}
